# WebSocket 配置检查脚本
# =====================

Write-Host "==================================" -ForegroundColor Cyan
Write-Host "WebSocket 配置检查工具" -ForegroundColor Cyan
Write-Host "==================================" -ForegroundColor Cyan
Write-Host ""

$rootDir = Split-Path -Parent $PSScriptRoot
$frontendDir = Join-Path $rootDir "frontend"
$envFile = Join-Path $frontendDir ".env"
$envExampleFile = Join-Path $frontendDir "env.example"

# 1. 检查环境变量文件
Write-Host "[1/5] 检查环境变量文件..." -ForegroundColor Yellow

if (Test-Path $envFile) {
    Write-Host "  ✓ .env 文件存在" -ForegroundColor Green
    $envContent = Get-Content $envFile -Raw
    
    if ($envContent -match "VITE_WS_URL=(.+)") {
        $wsUrl = $matches[1].Trim()
        Write-Host "  ✓ VITE_WS_URL = $wsUrl" -ForegroundColor Green
        
        if ($wsUrl -eq "ws://localhost:8004/api/v1/market") {
            Write-Host "  ✓ WebSocket URL 配置正确" -ForegroundColor Green
        } elseif ($wsUrl -eq "ws://localhost:8001") {
            Write-Host "  ✗ WebSocket URL 配置错误！应该是 ws://localhost:8004/api/v1/market" -ForegroundColor Red
            Write-Host "    当前配置: $wsUrl" -ForegroundColor Red
            Write-Host "    正在修复..." -ForegroundColor Yellow
            
            $envContent = $envContent -replace "VITE_WS_URL=ws://localhost:8001", "VITE_WS_URL=ws://localhost:8004/api/v1/market"
            Set-Content -Path $envFile -Value $envContent
            Write-Host "  ✓ 已修复 .env 文件" -ForegroundColor Green
        } else {
            Write-Host "  ⚠ WebSocket URL 配置异常: $wsUrl" -ForegroundColor Yellow
        }
    } else {
        Write-Host "  ✗ 未找到 VITE_WS_URL 配置" -ForegroundColor Red
    }
} else {
    Write-Host "  ✗ .env 文件不存在" -ForegroundColor Red
    Write-Host "    正在从 env.example 创建..." -ForegroundColor Yellow
    
    if (Test-Path $envExampleFile) {
        Copy-Item $envExampleFile $envFile
        Write-Host "  ✓ 已创建 .env 文件" -ForegroundColor Green
    } else {
        Write-Host "  ✗ env.example 文件也不存在" -ForegroundColor Red
    }
}

Write-Host ""

# 2. 检查后端服务配置
Write-Host "[2/5] 检查后端服务配置..." -ForegroundColor Yellow

$marketDataConfig = Join-Path $rootDir "backend\services\market_data_service\config\development.env"

if (Test-Path $marketDataConfig) {
    Write-Host "  ✓ market_data_service 配置文件存在" -ForegroundColor Green
    $configContent = Get-Content $marketDataConfig -Raw
    
    if ($configContent -match "PORT=(\d+)") {
        $port = $matches[1]
        Write-Host "  ✓ PORT = $port" -ForegroundColor Green
        
        if ($port -eq "8004") {
            Write-Host "  ✓ 端口配置正确" -ForegroundColor Green
        } else {
            Write-Host "  ⚠ 端口配置异常: $port (预期: 8004)" -ForegroundColor Yellow
        }
    }
} else {
    Write-Host "  ✗ market_data_service 配置文件不存在" -ForegroundColor Red
}

Write-Host ""

# 3. 检查服务运行状态
Write-Host "[3/5] 检查服务运行状态..." -ForegroundColor Yellow

try {
    $response = Invoke-WebRequest -Uri "http://localhost:8004/api/v1/market/health" -TimeoutSec 3 -ErrorAction Stop
    if ($response.StatusCode -eq 200) {
        Write-Host "  ✓ market_data_service 正在运行 (端口 8004)" -ForegroundColor Green
        
        $healthData = $response.Content | ConvertFrom-Json
        if ($healthData.success) {
            Write-Host "  ✓ 服务健康状态: 正常" -ForegroundColor Green
        }
    }
} catch {
    Write-Host "  ✗ market_data_service 未运行或无法访问" -ForegroundColor Red
    Write-Host "    请运行: python start_redfire_dev.py" -ForegroundColor Yellow
}

Write-Host ""

# 4. 检查 WebSocket 端点
Write-Host "[4/5] 检查 WebSocket 端点..." -ForegroundColor Yellow

try {
    $response = Invoke-WebRequest -Uri "http://localhost:8004/api/v1/market/ws/status" -TimeoutSec 3 -ErrorAction Stop
    if ($response.StatusCode -eq 200) {
        Write-Host "  ✓ WebSocket 服务可访问" -ForegroundColor Green
        
        $wsStatus = $response.Content | ConvertFrom-Json
        if ($wsStatus.success) {
            $activeConnections = $wsStatus.data.active_connections
            $subscriptionCount = $wsStatus.data.subscription_count
            Write-Host "  ✓ 活跃连接数: $activeConnections" -ForegroundColor Green
            Write-Host "  ✓ 订阅数量: $subscriptionCount" -ForegroundColor Green
        }
    }
} catch {
    Write-Host "  ⚠ 无法获取 WebSocket 状态" -ForegroundColor Yellow
    Write-Host "    这可能是正常的（如果服务刚启动）" -ForegroundColor Gray
}

Write-Host ""

# 5. 检查前端代码配置
Write-Host "[5/5] 检查前端代码配置..." -ForegroundColor Yellow

$smartMarketDataFile = Join-Path $rootDir "frontend\packages\api-client\src\hooks\useSmartMarketData.ts"

if (Test-Path $smartMarketDataFile) {
    Write-Host "  ✓ useSmartMarketData.ts 文件存在" -ForegroundColor Green
    
    $codeContent = Get-Content $smartMarketDataFile -Raw
    
    # 检查默认 WebSocket URL
    if ($codeContent -match "VITE_WS_URL.*\|\|.*'(ws://[^']+)'") {
        $defaultWsUrl = $matches[1]
        Write-Host "  ✓ 默认 WebSocket URL: $defaultWsUrl" -ForegroundColor Green
        
        if ($defaultWsUrl -eq "ws://localhost:8001") {
            Write-Host "  ⚠ 代码中的默认 URL 仍然是 8001 端口" -ForegroundColor Yellow
            Write-Host "    建议修改为: ws://localhost:8004/api/v1/market" -ForegroundColor Yellow
        }
    }
    
    # 检查策略阈值
    if ($codeContent -match "WEBSOCKET_MIN_FREQUENCY:\s*(\d+)") {
        $minFreq = $matches[1]
        Write-Host "  ✓ WebSocket 最小频率阈值: ${minFreq}ms" -ForegroundColor Green
    }
} else {
    Write-Host "  ✗ useSmartMarketData.ts 文件不存在" -ForegroundColor Red
}

Write-Host ""
Write-Host "==================================" -ForegroundColor Cyan
Write-Host "检查完成" -ForegroundColor Cyan
Write-Host "==================================" -ForegroundColor Cyan
Write-Host ""

# 生成建议
Write-Host "建议操作:" -ForegroundColor Cyan
Write-Host ""
Write-Host "1. 如果后端服务未运行，请执行:" -ForegroundColor White
Write-Host "   python start_redfire_dev.py" -ForegroundColor Gray
Write-Host ""
Write-Host "2. 如果修改了 .env 文件，请重启前端服务:" -ForegroundColor White
Write-Host "   cd frontend" -ForegroundColor Gray
Write-Host "   npm run dev" -ForegroundColor Gray
Write-Host ""
Write-Host "3. 在浏览器中验证 WebSocket 连接:" -ForegroundColor White
Write-Host "   - 打开开发者工具 (F12)" -ForegroundColor Gray
Write-Host "   - 切换到 Network 标签" -ForegroundColor Gray
Write-Host "   - 筛选 WS (WebSocket)" -ForegroundColor Gray
Write-Host "   - 应该看到连接到: ws://localhost:8004/api/v1/market/ws/market-data" -ForegroundColor Gray
Write-Host ""
Write-Host "4. 查看详细文档:" -ForegroundColor White
Write-Host "   docs/前端数据获取策略分析.md" -ForegroundColor Gray
Write-Host "   docs/WebSocket连接配置说明.md" -ForegroundColor Gray
Write-Host ""

